package stu.kurs.services.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import stu.kurs.domain.Category;

import stu.kurs.exceptions.ServiceException;
import stu.kurs.services.ICategoryService;


@Stateless(name="CategoryService")
public class CategoryService extends GenericService<Category> implements ICategoryService {

	public CategoryService() {
		super(Category.class);
	}

	@Override
	public void add(String name, String description) throws ServiceException {
		Category category = new Category(name, description);
		save(category);
		
	}

	@Override
	public void update(Integer id, String name, String description) throws ServiceException {
		Category category = findById(id);
		category.setName(name);
		category.setDescription(description);
		save(category);
		
	}

	@Override
	public void delete(Integer id) throws ServiceException {
		Category category = findById(id);
		delete(category);
		
		
	}
	
	@Override
	public List<Category> getAllCategory()	throws ServiceException {
		List<Category> result = null;
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Category> cq = cb.createQuery(Category.class);
		Root<Category> category = cq.from(Category.class);
		cq.orderBy(cb.asc(category.get("name")));
		cq.orderBy(cb.asc(category.get("description")));
		TypedQuery<Category> q = em.createQuery(cq); 
		try{
			result = q.getResultList();
		}
		catch (Exception e){
			throw new ServiceException(e);
		} 
		return result;
	}


}
